import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Upload, X, Image as ImageIcon } from 'lucide-react';

const ImageUploader = ({ 
  images = [], 
  onImagesChange, 
  maxImages = 8, 
  accept = "image/*",
  className = "" 
}) => {
  const [dragActive, setDragActive] = useState(false);

  // 处理文件上传
  const handleFiles = (files) => {
    const fileArray = Array.from(files);
    const newImages = fileArray.map(file => ({
      id: Date.now() + Math.random(),
      url: URL.createObjectURL(file),
      file: file,
      name: file.name
    }));
    
    const updatedImages = [...images, ...newImages].slice(0, maxImages);
    onImagesChange && onImagesChange(updatedImages);
  };

  // 处理拖拽事件
  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      setDragActive(true);
    } else if (e.type === "dragleave") {
      setDragActive(false);
    }
  };

  // 处理拖拽放下
  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFiles(e.dataTransfer.files);
    }
  };

  // 处理文件选择
  const handleFileSelect = (e) => {
    if (e.target.files && e.target.files[0]) {
      handleFiles(e.target.files);
    }
  };

  // 删除图片
  const handleRemoveImage = (imageId) => {
    const updatedImages = images.filter(img => img.id !== imageId);
    onImagesChange && onImagesChange(updatedImages);
  };

  // 重新排序图片
  const handleReorder = (fromIndex, toIndex) => {
    const updatedImages = [...images];
    const [movedImage] = updatedImages.splice(fromIndex, 1);
    updatedImages.splice(toIndex, 0, movedImage);
    onImagesChange && onImagesChange(updatedImages);
  };

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 图片预览区域 */}
      {images.length > 0 && (
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {images.map((image, index) => (
            <div key={image.id} className="relative group">
              <img
                src={image.url}
                alt={image.name || '商品图片'}
                className="w-full h-24 object-cover rounded border"
              />
              
              {/* 删除按钮 */}
              <button
                type="button"
                onClick={() => handleRemoveImage(image.id)}
                className="absolute top-1 right-1 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                title="删除图片"
              >
                <X className="size-3" />
              </button>
              
              {/* 排序指示器 */}
              <div className="absolute bottom-1 left-1 bg-black/50 text-white text-xs px-1 rounded">
                {index + 1}
              </div>
              
              {/* 拖拽手柄 */}
              <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                <ImageIcon className="size-6 text-white" />
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 上传区域 */}
      {images.length < maxImages && (
        <div
          className={`border-2 border-dashed rounded-lg p-6 text-center transition-colors ${
            dragActive 
              ? 'border-primary bg-primary/5' 
              : 'border-muted-foreground/25 hover:border-muted-foreground/50'
          }`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
        >
          <div className="space-y-2">
            <Upload className="size-8 mx-auto text-muted-foreground" />
            <div className="text-sm text-muted-foreground">
              <p>拖拽图片到此处或</p>
              <label className="cursor-pointer text-primary hover:text-primary/80">
                <span>点击选择文件</span>
                <input
                  type="file"
                  accept={accept}
                  multiple
                  onChange={handleFileSelect}
                  className="hidden"
                />
              </label>
            </div>
            <p className="text-xs text-muted-foreground">
              支持 JPG、PNG、GIF 格式，最多 {maxImages} 张图片
            </p>
          </div>
        </div>
      )}

      {/* 上传按钮（备用） */}
      {images.length < maxImages && (
        <div className="flex justify-center">
          <Button variant="outline" asChild>
            <label>
              <Upload className="size-4 me-2" />
              选择图片
              <input
                type="file"
                accept={accept}
                multiple
                onChange={handleFileSelect}
                className="hidden"
              />
            </label>
          </Button>
        </div>
      )}

      {/* 图片数量提示 */}
      <div className="text-xs text-muted-foreground text-center">
        已上传 {images.length} / {maxImages} 张图片
      </div>
    </div>
  );
};

export default ImageUploader; 